package com.oa.xinxi.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oa.login.entity.Emp;
import com.oa.office.util.UtilHelp;
import com.oa.xinxi.biz.SpeechBiz;
import com.oa.xinxi.entity.LeaderSpeech;
import com.oa.xinxi.utils.Constants;

@Controller
@RequestMapping("/speech")
public class SpeechController {
	@Resource
	private SpeechBiz speechBiz;
	@Resource
	private UtilHelp utilHelp;
	@RequestMapping("/list")
	public String list(Model model,@RequestParam(required=true,defaultValue="1") Integer page) {
		PageHelper.startPage(page, 10);
		List<LeaderSpeech> list = speechBiz.findAll();
		PageInfo<LeaderSpeech> p=new PageInfo<LeaderSpeech>(list);
		model.addAttribute("list", list);
		model.addAttribute("page", p);
		return "/xinxi/speech/list";
	}
	@RequestMapping("/preAdd")
	public String add() {
		return "/xinxi/speech/add";
	}
	@RequestMapping("/add")
	public String save(LeaderSpeech speech,HttpSession session,MultipartHttpServletRequest request) {
//		System.out.println("添加");
		MultipartFile file = request.getFile("file");
//		String path = request.getSession().getServletContext().getRealPath("upload"); 
		String path = utilHelp.getPath();
        String fileName = file.getOriginalFilename(); 
        StringBuffer sb = new StringBuffer();
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
//        dateString.replace(" ", "");
//        dateString.replaceAll(":", "");
        sb.append(dateString).append(fileName);
//        String fileName = new Date().getTime()+".jpg";  
        System.out.println(path);  
        File targetFile = new File(path, sb.toString());  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
        //保存  
        try {  
            file.transferTo(targetFile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
		speech.setUploadWj(sb.toString());
//        speech.setUploadWj("1.xlsl");
		Emp emp = (Emp)session.getAttribute("emp");
		speech.setCreator(emp.getEmpName());
		speechBiz.save(speech);
		return "redirect:/speech/list";
	}
	/**
     * 文件下载
     * @Description: 
     * @param fileName
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/{name}/download")
    public void downloadFile(@PathVariable("name")String name,
            HttpServletRequest request, HttpServletResponse response) {
    	try {
			name = new String(name.getBytes("ISO-8859-1"), "utf8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
//    	response.setHeader("Content-Disposition", "attachment;filename=1.xlsx");
    	String path = utilHelp.getPath();
    	File file = new File(path+File.separator+name);
		if (file.exists()) {
			try {
				response.setHeader("Content-Disposition", "attachment;filename="+name);
				FileInputStream fis = new FileInputStream(file);
				OutputStream os = response.getOutputStream();
				byte[] b = new byte[1024];
				int len = 0;
				while ((len = fis.read(b)) != -1) {
					os.write(b, 0, len);
				}
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			
		}
    }
	@RequestMapping("/detail/{id}")
	public String detail(Model model,@PathVariable("id") int id) {
		LeaderSpeech speech = speechBiz.findById(id);
		model.addAttribute("speech", speech);
		return "/xinxi/speech/detail";
	}
	@RequestMapping("/delete/{id}")
	public String deleteById(Model model,@PathVariable("id") int id) {
		speechBiz.deleteById(id);
		return "redirect:/speech/list";
	}
	@RequestMapping("/preUpdate/{id}")
	public String updateById(Model model,@PathVariable("id") int id) {
		LeaderSpeech speech = speechBiz.findById(id);
		 model.addAttribute("speech", speech);
		return "/xinxi/speech/update";
	}
	@RequestMapping("/update")
	public String DoUpdateById(LeaderSpeech speech,HttpSession session) {
//		System.out.println(news.getContent());
		Emp emp = (Emp)session.getAttribute("emp");
		speech.setUpdator(emp.getEmpName());
		speechBiz.update(speech);
		return "redirect:/speech/list";
	}
}
